'use strict';

angular.module('backofficeApp.backendUser.controllers',[]).
    controller('backendUserCtrl',['$scope','$location','$filter','$http','backendUserCommunityService','backendUserService','CommunityService','$routeParams','getAllUnbindedServiceUser',
        function($scope,$location,$filter,$http,backendUserCommunityService,backendUserService,communityService,$routeParams,getAllUnbindedServiceUser){

        $scope.$watch('$viewContentLoaded', function () {
            //$http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/100', {
            //    headers: {'Content-Type': 'application/json;charset=utf-8'}
            //}).success(function (result) {
            //    $scope.backendUserList = result.data.items;
            //}).error(function () {
            //});

            $scope.communityLabelList = communityService.getAllCommunityService(function(data){

                if(data.data){
                    var selectList = [];
                    data.data.forEach(function(item){
                        var a = {};
                        a.name = item.communityName;
                        a.id = item.objId;
                        selectList.push(a);
                    });
                    new select({data:selectList,id:"community_select"});
                };
            });

        });

        $scope.currentPage = 0;
        $scope.totalPage =0;
        $scope.pageSize = 20;
        $scope.getAdminUserList = function () {
            var commId = $("#community_select")[0].dataset.cId;
            var opt ={
            };
            if(commId){
                opt.communities = commId;
            }
            if($scope.role!= null &&$scope.role!= ""){
                opt.role = $scope.role;
            };
            if($scope.loginName != null && $scope.loginName != ""){
                opt.userName = $scope.loginName;
            };

            if($scope.currentPage == 0){
                $scope.currentPage = 1;
            };
            console.debug(opt);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/getAdminUserListPaging/'+  $scope.currentPage + '/'+ $scope.pageSize, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.totalPage = result.data.totalPage;
                $scope.backendUserList = result.data.backendUserList;
            });

        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getAdminUserList();
        };

        var selectMenu ={
            create:function(data,select){
                for(var i in data)
                {
                    var option=data[i];
                    if(option&&option.objId&&option.communityName) {
                        var value = option.objId;
                        var text = option.communityName;
                        this.menu.append("<option value='" + value + "'>" + text + "</option>");
                    }

                }
            },
            clear:function(){
                this.menu.children().remove();
            },
            getValue:function(){
                var communities=[];
                this.menu.find("option").each(function(){
                    communities.push($(this).val());
                });
                return communities;
            }
        };

        var userMenu ={
            create:function(data, selected){
                for(var i in data)
                {
                    var option=data[i];
                    if(option&&option.objId&&option.mobilePhone) {
                        var value = option.objId;
                        var text = option.mobilePhone;
                        this.menu.append("<option "+selected+" value='" + value + "'>" + text + "</option>");
                    }

                }
            },
            clear:function(){
                this.menu.children().remove();
            },
            getValue:function(){
                var communities=[];
                this.menu.find("option:selected").each(function(){
                    communities.push($(this).val());
                });
                return communities;
            }
        };
        var serviceStr="Service";
            $scope.commList = [];
        //===========================================================
        $scope.onRoleChange=function(status){
                            if (value === status) {
                                role_select.show()
                            }
                            else {
                                role_select.hide()
                            }
        }
        $scope.addUser=function(){
            $scope.oldPasswordDisplay = false;
            $('#user_modal').modal('show');
            backendUserCommunityService.get(function(res){
                selectMenu.menu=$('#communities_select');
                selectMenu.clear();
                selectMenu.create(res.data,"");
                $("#selCommunitys").html("");
                $scope.commList = res.data;
            });


            getAllUnbindedServiceUser.get(function(res){
                userMenu.menu=$('#user_select');
                userMenu.clear();
                userMenu.create(res.data,"");
            });

            $scope.backendUser=null;
            $scope.popupTitle = "Create a new backend User...";
            $("#loginId").prop('disabled', false);
            $('#saveButton').show();
            $('#updateButton').hide();

        };
        $scope.saveAdd=function(backendUser){
            selectMenu.menu=$('#selCommunitys');
            backendUser.communities=selectMenu.getValue();
            if(backendUser.password!=backendUser.password2){
                $scope.matchFlag=false;
                return;
            }
            //selectMenu.menu=$('#communities_select');
            //backendUser.communities=selectMenu.getValue();
            userMenu.menu=$('#user_select');
            if(userMenu.getValue().length==1){
                backendUser.appuser=userMenu.getValue()[0]
            }

            if($scope.backendUser.role == "moderator" || $scope.backendUser.role == "Property"){

                if($scope.appUser == null || $scope.appUser == ""){
                    alert('请填写应用登录ID!');
                    return;
                };

                //判断绑定的appUser是否存在
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getUser', {'_id':$scope.appUser}, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {

                    //判断当前用户名是否存在
                    //$http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getUser', {'_id':$scope.appUser}, {
                    //    headers: {'Content-Type': 'application/json;charset=utf-8'}
                    //}).success(function (data) {

                        //if(data.data != null){
                        //alert('用户ID或用户名重复!')
                        //
                        //}else {
                            //绑定的appUser存在
                            if (data.data != null) {

                                backendUser.appuser = $scope.appUser;
                                //添加后台用户
                                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser', backendUser, {
                                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                                }).success(function (data) {

                                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/50', {
                                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                                    }).success(function (result) {
                                        $scope.backendUserList = result.data.items;
                                        $('#user_modal').modal('hide');
                                    }).error(function () {
                                    });

                                }).error(function () {
                                    alert('保存失败!')
                                });
                                ;
                            } else {
                                alert('应用登录ID不存在!')
                            }
                        //}
                    });
                //});

            }else {
                //添加后台用户
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser', backendUser, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    var isFreshlist = true;
                    if (data.result.status == 1) {
                        if (data.data.role === "Service" && !data.data.appuser) {
                            isFreshlist = false;
                            //backendUserService.get({serviceId: data.data.objId}, function (res) {
                            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/admin/createUserForService/'+ data.data.objId +'/'+ data.data.communities[0],{

                            }).success(function(data){

                                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                                }).success(function (result) {
                                    $scope.backendUserList = result.data.items;
                                    $('#user_modal').modal('hide');
                                }).error(function () {
                                });
                            });
                        }
                    }
                    if (isFreshlist) {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.backendUserList = result.data.items;
                            $('#user_modal').modal('hide');
                        }).error(function () {
                        });
                    }
                }).error(function (data) {

                });

            }
        };
        //=========================================================
        $scope.oldAppUser = null;
        $scope.updateUser=function(loginId){
            $scope.oldPasswordDisplay = true;
            $scope.commList = [];
            $('#selCommunitys').html('');
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/findByLoginId/'+loginId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                //$scope.oldPassword = result.data.password;
                $scope.backendUser = result.data;
                result.data.newPassword = "";
                $scope.backendUser.newPassword2 = "";

                $('#user_modal').modal('show');
                $("#loginId").prop('disabled', true);
                $('#saveButton').hide();
                $('#updateButton').show();
                $scope.popupTitle = "Update the backend User...";
                selectMenu.menu=$('#communities_select');
                selectMenu.clear();
                //selectMenu.create(result.data.communities,"selected");
                //$scope.commList = result.data.communities;
                if(result.data.appuser != null) {
                    $scope.appUser = result.data.appuser.objId;
                    $scope.oldAppUser = result.data.appuser.objId;
                }
                backendUserCommunityService.get(function(res){
                    selectMenu.create(res.data,"");
                    for(var i = 0;i < result.data.communities.length;i++)
                    {
                        var userComm=result.data.communities[i];
                        for(var j in res.data){
                            var comm=res.data[j];
                            if(userComm.objId==comm.objId)
                            {
                                delete res.data[j];
                                $("#communities_select option[value="+comm.objId+"]").appendTo('#selCommunitys');
                                //console.log(comm)
                            }
                        }
                    }

                    res.data.forEach(function(item){
                        $scope.commList.push(item);
                    });
                });

                userMenu.menu=$('#user_select');
                userMenu.clear();
                userMenu.create([result.data.appuser],"selected");
                getAllUnbindedServiceUser.get(function(res){
                    userMenu.create(res.data,"");
                });

            }).error(function (result) {
                alert('Error Happened from when trying to get the backend frontendUser information...');
            });
        };

        $scope.saveUpdate=function(loginId,backendUser){
            selectMenu.menu=$('#selCommunitys');
            backendUser.communities=selectMenu.getValue();

            //修改密码
            if(backendUser.newPassword || backendUser.newPassword2){
                if(backendUser.oldPassword == null || $scope.oldPassword == ""){
                    alert("请输入原密码!");return;
                }else if(backendUser.newPassword != backendUser.newPassword2){
                    alert("两次输入密码不相等!");return;
                };
            };

            if(!backendUser.newPassword && !backendUser.newPassword2){
               if(backendUser.oldPassword){
                   alert("请输入新密码!");return;
               };
            };

            if($scope.backendUser.role =="moderator" || $scope.backendUser.role =="Property"){
                if($scope.appUser == null || $scope.appUser == ""){
                    alert('请填写应用登录ID!');
                    return;
                };
            };

            if($scope.backendUser.role == "Service") {
                userMenu.menu=$('#user_select');
                if (userMenu.getValue().length == 1) {
                    backendUser.appuser = userMenu.getValue()[0]
                } else {
                    backendUser.appuser = undefined;
                }
            }else{
                backendUser.appuser = $scope.appUser;
                backendUser.oldAppUser = $scope.oldAppUser;
            };
            //console.debug(backendUser);
            $('#user_modal').modal('hide');
            $http.put('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/'+loginId, backendUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if(data.result.status == 0){
                    alert(data.result.message);
                    return;
                }else {

                    $scope.getAdminUserList();

                    //$http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserListPaging/'+  $scope.currentPage + '/'+ $scope.pageSize, opt, {
                    //    headers: {'Content-Type': 'application/json;charset=utf-8'}
                    //}).success(function (result) {
                    //    $scope.backendUserList = result.data.items;
                    //}).error(function () {
                    //
                    //});
                }
            }).error(function (data) {
                alert('Error Happened from when trying to Update the backend frontendUser information...');
            });
        };

        $scope.deleteUser=function(loginId){
            //bootbox.classes.add('medium');
            bootbox.confirm("Are you sure want to delete?", function(result) {
                if(result==true){
                    $http.delete('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/'+loginId, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.backendUserList = result.data.items;
                        }).error(function () {
                        });
                    }).error(function (result) {
                        alert('Error Happened from when trying to get the backend frontendUser information...');
                    });
                }
            }).find("div.modal-dialog").css({ width: '30%'});
           // bootbox.alert("Hello").find("div.modal-dialog").addClass("largeWidth");

        }

        $scope.changePassword1Value = function(){
            $scope.matchFlag=true;
        }
        $scope.changePassword2Value = function(){
            $scope.matchFlag=true;
        };
        $scope.roleChange = function() {
            $scope.appUser = "";
        };

        //全部移到右边
        $scope.addAllCommunity = function () {
            //获取全部的选项,删除并追加给对方
            $('#communities_select option').appendTo('#selCommunitys');
            $scope.commList = [];
        };

        //全部移到左边
        $scope.removeAllCommunity = function () {
            var selectedCom = $('#selCommunitys option');
            for(var i = 0;i < selectedCom.length;i++){
                var item = {objId:selectedCom[i].value,communityName:selectedCom[i].label};
                $scope.commList.push(item);
            }

            $('#selCommunitys option').appendTo('#communities_select');
        };
            //移到右边
        $scope.addCommunity = function () {
            var selectedCom = $('#communities_select option:selected');
            for(var i = 0;i < selectedCom.length;i++){
                for(var j in $scope.commList){
                    if(selectedCom[i].value == $scope.commList[j].objId)$scope.commList.splice(j,1);
                }
            }
                //先判断是否有选中
                if (!$("#communities_select option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                //获取选中的选项，删除并追加给对方
                else {
                    $('#communities_select option:selected').appendTo('#selCommunitys');
                }
            };

            //移到左边
        $scope.removeCommunity = function () {
            var selectedCom = $('#selCommunitys option:selected');
            for(var i = 0;i < selectedCom.length;i++){
                var item = {objId:selectedCom[i].value,communityName:selectedCom[i].label};
                $scope.commList.push(item);
            }
                //先判断是否有选中
                if (!$("#selCommunitys option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                else {
                    $('#selCommunitys option:selected').appendTo('#communities_select');
                }
            };

        $scope.cnameFilter = function(name){
                var html = "";
                $scope.commList.forEach(function(item){
                    if(item.communityName.match(name)){
                        html += "<option value="+item.objId+">"+item.communityName+"</option>";
                    }
                    $("#communities_select").html(html);
                });
            };

            $(document).on("dblclick","#communities_select option",function(){
                $(this).appendTo('#selCommunitys');
            });
            $(document).on("dblclick","#selCommunitys option",function(){
                $(this).appendTo('#communities_select');
            });

    }]).directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {

                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.numPages ? scope.numPages : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('numPages', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.numPages;
                };

            }
        };
    });;


angular.module('backofficeApp.backendUser.services', ['ngResource']).
    factory('backendUserCommunityService', function ($resource) {
        return $resource('/rest/v1.0/backoffice/admin/availableCommunities', {}, {});
    }).
    factory('backendUserService',function($resource){
        return $resource('/rest/v1.0/backoffice/admin/createUserForService/:serviceId', {serviceId:'@serviceId'}, {});
    }).
    factory('getAllUnbindedServiceUser',function($resource){
        return $resource('/rest/v1.0/backoffice/admin/getAllUnbindedServiceUser', {}, {});
    })

